# -*- coding: utf-8 -*-
import json
from pyquery import PyQuery
from datetime import datetime
from zc_core.util.encrypt_util import md5
from zc_core.model.items import *
from zc_core.util.sku_id_parser import convert_id2code

from chinagd.utils.catalog_helper import CatalogHelper


def parse_catalog_index(response):
    if not response.text:
        return None
    cat_list = list()
    doc = PyQuery(response.text)
    cats = doc(".f14 li")
    for cat1 in cats.items():
        cat_name = cat1("a").text().strip()
        cat_id = cat1.attr("data-guidecid").strip()
        cat_list.append(build_catalog(cat_id, cat_name, 1))

    return cat_list


def parse_catalog_detail(response):
    if not response.text:
        return None
    meta = response.meta
    cat2_parent_id = meta.get("catalogId")
    cat_list = list()
    cat_json = json.loads(response.text)
    cats = cat_json.get("data", {}).get("rows", {})
    for cat2 in cats:
        cat2_name = cat2.get("catalogName")
        cat2_id = str(cat2.get("guideCatalogId"))
        cat_list.append(build_catalog(cat2_id, cat2_name, 2, cat2_parent_id))

        childs = cat2.get("rows", [])
        if len(childs) > 0:
            for cat3 in childs:
                cat3_name = cat3.get("catalogName")
                cat3_id = str(cat3.get("guideCatalogId"))
                cat_list.append(build_catalog(cat3_id, cat3_name, 3, cat2_id))

    return cat_list


def build_catalog(id, name, level, parent_id=None):
    entity = Catalog()

    entity['catalogId'] = id
    entity['catalogName'] = name
    entity['parentId'] = parent_id
    entity['level'] = level
    if entity['level'] == 3:
        entity['leafFlag'] = 1
    else:
        entity['leafFlag'] = 0
    entity['linkable'] = 0
    return entity


def parse_sku_list(response):
    if not response.text:
        return None
    content = json.loads(response.text)
    skus = content.get('data', {}).get('result')
    sku_list = list()
    if skus and len(skus) > 0:
        meta = response.meta
        batch_no = meta.get('batchNo')
        for sku in skus:
            entity = Sku()
            entity['batchNo'] = batch_no
            entity['skuId'] = str(sku.get("skuId"))
            entity['supplierId'] = str(sku.get("supplierId"))
            entity['supplierName'] = sku.get("supplierName")
            market_price = sku.get("marketPrice")
            if market_price:
                market_price = float(market_price)
                entity['originPrice'] = market_price
            sale_price = sku.get('salePrice')
            if sale_price:
                sale_price = float(sku.get("salePrice"))
                entity['salePrice'] = sale_price
            sku_list.append(entity)

    return sku_list


def fill_sku_params(params):
    param_list = []
    dict = {"filterId": "l3_category_id_name", "filterName": "分类"}
    for key, value in params.items():
        dict[key] = value
    param_list.append(dict)
    return param_list


def parse_item_data(response):
    cat_helper = CatalogHelper()
    json_data = json.loads(response.text)
    item_data = json_data.get('data')
    if not item_data:
        return None
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    supplier_id = meta.get('supplierId')
    supplier_name = meta.get('supplierName')
    origin_price = meta.get('originPrice')
    sale_price = meta.get('salePrice')
    material_code = meta.get('materialCode')

    brand_name = item_data.get('brandName')
    brand_id = md5(brand_name)
    brand_model = item_data.get('unit')
    sku_img = item_data.get('imagePath')
    sku_name = item_data.get('name')
    unit = item_data.get("saleUnit")
    spu_id = item_data.get("upc")
    cats = item_data.get('categories')

    item = ItemData()
    item['batchNo'] = batch_no
    item['skuId'] = sku_id
    item['materialCode'] = material_code
    item['brandId'] = brand_id
    item['brandModel'] = brand_model
    item['brandName'] = brand_name
    if cats and len(cats) > 0:
        catalog3_id = cats[-1]
        item['catalog3Id'] = catalog3_id
        cat_helper.fill(item)

    item['originPrice'] = origin_price
    item['salePrice'] = sale_price
    if sku_img:
        item['skuImg'] = parse_image_url(sku_img, supplier_name)
    item['skuName'] = sku_name
    item['supplierId'] = supplier_id
    item['supplierName'] = supplier_name
    item['unit'] = unit
    item['spuId'] = spu_id

    sp_sku_id = item_data.get("sku")
    if sp_sku_id:
        item['supplierSkuId'] = sp_sku_id
        plat_code = None
        if item['supplierId'] == '3' or '得力' in item['supplierName']:
            plat_code = 'deli'
        item['supplierSkuCode'] = convert_id2code(plat_code, sp_sku_id)

    item['genTime'] = datetime.utcnow()
    return item


def parse_image_url(url, plat_name):
    deli_url = "http://b2bimgcdn.nbdeli.com/n1/"
    domain = "http://img13.360buyimg.com/n0/"

    if 'http://' not in url:
        if plat_name == '得力':
            return deli_url + url
        else:
            return domain + url
    else:
        return url


def parse_sales(response):
    meta = response.meta
    item = meta.get('itemData')
    sales_data = json.loads(response.text).get('data', {})
    if sales_data and sales_data.get('saleNum'):
        item['soldCount'] = int(sales_data.get('saleNum'))
    else:
        item['soldCount'] = 0
    return item


def parse_mdm(response):
    sku_data = json.loads(response.text).get('data', {})
    if sku_data:
        mdm_list = sku_data.get('shMdmCode', [])
        if mdm_list:
            item = ItemDataSupply()
            item['skuId'] = str(sku_data.get('skuId'))
            item['materialCode'] = str(mdm_list[0])
            return item
    return None


def parse_supplier_list(response):
    if not response.text:
        return None
    meta = response.meta
    batch_no = meta.get('batchNo')
    docs = PyQuery(response.text)
    supplier_docs = docs('.logo-div')
    suppliers = list()
    if supplier_docs:
        for sp_doc in supplier_docs.items():
            supplier = Supplier()
            supplier['id'] = sp_doc.attr("data-id").strip()
            supplier['name'] = sp_doc.attr("data-val").strip()
            supplier['batchNo'] = batch_no
            suppliers.append(supplier)
    return suppliers
